<template>
  <div class="menu-add-edit">
    <a-form name="advanced_search" autoComplete="off" class="menu-form" :model="formState" ref="menuAddFrom">
      <a-form-item :label="formState.menuSuperior.label" :name="['menuSuperior', 'value']"
        :rules="[formState.menuSuperior.rule]">
        <a-tree-select class="AtreeSelect" v-model:value="formState.menuSuperior.value" ref="usermanage_treeSelect"
          :placeholder="formState.menuSuperior.placeholder" show-search
          :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" allow-clear treeNodeFilterProp="menuName"
          :fieldNames="{
            children: 'children',
            label: 'menuName',
            value: 'id',
          }" tree-default-expand-all :tree-data="parendData" @select="selectParent">
        </a-tree-select>
      </a-form-item>
      <a-form-item :name="['entryPage', 'value']" :label="formState.entryPage.label" :rules="[formState.entryPage.rule]">
        <a-input v-model:value="formState.entryPage.value" :placeholder="formState.entryPage.placeholder" show-count
          :maxlength="200" allow-clear />
      </a-form-item>
      <a-form-item :name="['menuName', 'value']" :label="formState.menuName.label" :rules="[formState.menuName.rule]">
        <a-input v-model:value="formState.menuName.value" :placeholder="formState.menuName.placeholder" show-count
          :maxlength="25" allow-clear />
      </a-form-item>
      <a-form-item class="menus-item" :name="['menuLogo', 'value']" :label="formState.menuLogo.label"
        :rules="[formState.menuLogo.rule]">
        <a-input v-model:value="formState.menuLogo.value" :placeholder="formState.menuLogo.placeholder" allow-clear
          v-if="isMenu && menuType == 1" />
        <a-select v-model:value="formState.menuLogo.value" placeholder="请选择" style="width: 362px" :options="buttonOptions"
          v-if="!isMenu && menuType == 2"></a-select>
        <a-select v-model:value="formState.menuLogo.value" laceholder="请选择" style="width: 362px" :options="menuOptions"
          v-if="menuType == 3"></a-select>
      </a-form-item>
      <a-form-item v-if="isMenu" :name="['menuAddress', 'value']" :label="formState.menuAddress.label"
        :rules="[formState.menuAddress.rule]">
        <a-input v-model:value="formState.menuAddress.value" :placeholder="formState.menuAddress.placeholder"
          allow-clear />
      </a-form-item>
      <a-form-item v-if="isMenu" :name="['component', 'value']" :label="formState.component.label"
        :rules="[formState.component.rule]">
        <a-input v-model:value="formState.component.value" allow-clear />
      </a-form-item>
      <!-- <a-form-item v-if="isMenu" :name="['redirect', 'value']" :label="formState.redirect.label"
        :rules="[formState.redirect.rule]">
        <a-input v-model:value="formState.redirect.value" allow-clear />
      </a-form-item> -->
      <a-form-item v-if="isMenu" :name="['meta', 'value']" :label="formState.meta.label" :rules="[formState.meta.rule]">
        <a-input v-model:value="formState.meta.value" allow-clear />
      </a-form-item>
      <a-form-item :name="['isShow', 'value']" :label="formState.isShow.label" :rules="[formState.isShow.rule]">
        <a-switch size="small" v-model:checked="formState.isShow.value" />
      </a-form-item>
      <!-- <a-form-item :name="['isAuth', 'value']" :label="formState.isAuth.label" :rules="[formState.isAuth.rule]">
        <a-switch size="small" v-model:checked="formState.isAuth.value" />
      </a-form-item> -->
      <a-form-item class="menus-item" :name="['menuType', 'value']" :label="formState.menuType.label"
        :rules="[formState.menuType.rule]">
        <a-select v-model:value="formState.menuType.value" @change="changeType" placeholder="请选择"
          :options="menuTypeOptions"></a-select>
      </a-form-item>
      <a-form-item class="menus-item" :name="['menuSort', 'value']" :label="formState.menuSort.label"
        :rules="[formState.menuSort.rule]">
        <a-input v-model:value="formState.menuSort.value" :placeholder="formState.menuSort.placeholder" allow-clear />
      </a-form-item>
      <a-form-item v-if="isMenu" class="tag-item" :name="['menuIcon', 'value']" :label="formState.menuIcon.label"
        :rules="[formState.menuIcon.rule]">
        <upload :fileList="fileList" :isAutoUpload="true" @uploadFinished="uploadFinished" :maxCount="1" :title="'上传图标'">
        </upload>
      </a-form-item>
      <!-- <a-form-item class="tag-item" :name="['apiQuth', 'value']" :label="formState.apiQuth.label"
        :rules="[formState.apiQuth.rule]">
        <a-button type="primary" @click="selectApi"> 请选择 </a-button>
        <template v-if="selectApiList.length">
          <div v-for="item in selectApiList" class="selctapi-list">
            <a-tag :closable="true" @close="closeItem(item)">
              {{ item?.name || item?.apiName }}
            </a-tag>
          </div>
        </template>
      </a-form-item> -->
    </a-form>

    <!-- 选择api权限模态框 -->
    <!-- <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
      <template v-slot:body>
        <div class="add-item">
          <div class="header-content">
            <span>已选择列表</span>
            <template v-if="selectApiList.length">
              <div v-for="item in selectApiList" class="selctapi-list">
                <a-tag :closable="true" @close="closeItem(item)">
                  {{ item?.name || item?.apiName }}
                </a-tag>
              </div>
              <a-button class="closeAll" @click="closeAll">全部清除</a-button>
            </template>
            <div class="searchContent">
              <a-input v-model:value="apiName" placeholder="API名称" style="width: 192px">
                <template #suffix>
                  <i class="iconfont icon-search" @click="onSearch"></i>
                </template>
              </a-input>
            </div>
          </div>
          <div class="baseTable">
            <baseTable :columns="columns.selectapiColumn" :dataSource="configData.records" :isSelect="true"
              :scroll="{ y: 400 }" ref="selectApiTables" :isShowPagination="isShowPagination"
              :showCheckDelete="showCheckDelete" :total="configData.total" @changePage="changePage">
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.ellipsis">
                  <table-tool-tip :text="text" :column="column"></table-tool-tip>
                </template>
              </template>
            </baseTable>
          </div>
        </div>
      </template>
    </base-modal> -->
  </div>
  <div class="saveBtn" :style="styleWidth">
    <a-button type="primary" :disabled="saveAble" @click="saveSetting" style="margin-right: 8px">
      保存
    </a-button>
    <a-button @click="cancle"> 取消 </a-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import upload from "@/components/upload/uploadFile.vue";
import { Modal, message } from "ant-design-vue";
import baseTable from "@/components/table/baseTable.vue";
import baseModal from "@/components/modal/baseModal.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import { useRoute, useRouter } from "vue-router";
import { buttonOptions, menuOptions } from "./buttonOptions";
import { scrollType, modeProp, detailDataItemType } from "@/type.d";
import request from "@/api/index";
import { routerPerm } from '@/utils/common';

const parendData = ref<detailDataItemType>([]);

interface dataSourceType {
  [propName: string]: any;
}

//data
const saveAble = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "L",
  title: "API权限设置",
});
//表格数据
const isShowPagination = true; // 是否需要配分页器
let configData = reactive<dataSourceType>({ total: 0, size: 10, records: [] });
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const route: any = useRoute();
const router: any = useRouter();
const fileList = ref<any>([]);
const selectApiList = ref<dataSourceType[]>([]);
const isVisible = ref<boolean>(false);
const menuAddFrom = ref<any>("menuAddFrom");
const apiName = ref<string>("");
let rowSelection = ref<any[]>([]);
let apiIds = ref<any[]>([]);
const selectApiTables = ref<any>(null);
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let datas = reactive<any>({});
const menuType = ref<number>(1);
const isMenu = ref<boolean>(true);
const menuTypeOptions = ref([
  { type: 1, value: "菜单" },
  { type: 2, value: "按钮" },
  { type: 3, value: "菜单按钮" },
]);

const formState = reactive<dataSourceType>({
  menuSuperior: {
    value: null,
    placeholder: "请选择上级菜单",
    rule: {
      required: false,
      trigger: ["change", "blur"],
    },
    label: "上级菜单",
  },
  entryPage: {
    value: '',
    placeholder: "请填写入口页面地址",
    rule: {
      required: false,
      trigger: ["change", "blur"],
    },
    label: "入口页面",
  },
  menuName: {
    value: "",
    placeholder: "请输入菜单名称",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "菜单名称不能为空！",
    },
    label: "菜单名称",
  },
  component: {
    value: "",
    rule: {
      required: false,
      // trigger: ["blur"],
      // message: "文件名称不能为空！",
    },
    label: "文件名称",
  },
  meta: {
    value: "",
    rule: {
      required: false,
      // trigger: ["change", "blur"],
      // message: "文件名称不能为空！",
    },
    label: "路由信息",
  },
  redirect: {
    value: "",
    rule: {
      required: false,
      // trigger: ["change", "blur"],
      // message: "文件名称不能为空！",
    },
    label: "重定向地址",
  },
  menuLogo: {
    value: "",
    placeholder: "请输入菜单标识",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "菜单标识不能为空！",
    },
    label: "菜单标识",
  },
  menuAddress: {
    value: "",
    placeholder: "请输入路由地址",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "路由地址不能为空！",
    },
    label: "路由地址",
  },
  isShow: {
    value: true,
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "",
    },
    label: "是否显示",
  },
  // isAuth: {
  //   value: false,
  //   rule: {
  //     required: false,
  //     trigger: ["blur"],
  //     message: "",
  //   },
  //   label: "是否权限控制",
  // },
  menuType: {
    value: "菜单",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "菜单类型不能为空！",
    },
    label: "菜单类型",
  },
  menuSort: {
    value: "",
    placeholder: "请输入菜单排序",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "菜单排序不能为空！",
    },
    label: "菜单排序",
  },
  menuIcon: {
    value: "",
    rule: {
      required: false,
      trigger: ["change", "blur"],
      message: "",
    },
    label: "菜单图标",
  },
  // apiQuth: {
  //   value: "",
  //   rule: {
  //     required: false,
  //     trigger: [""],
  //     message: "",
  //   },
  //   label: "API权限",
  // },
  routePath: "",
  parentId: "",
  id: "",
});
const pageNumber = ref<number>(1);
const pageSize = ref<number>(10);
//method
const init = () => {
  if (route.query.menuType == 2) {
    isMenu.value = false;
  } else {
    isMenu.value = true;
  }
};
const getMenuAllTree = async () => {
  parendData.value = (await request.fetchMenuAlltree({})) || [];
};

const selectParent = (e: string, options: any) => {
  //获取上级菜单id
  formState.parentId = e;
};

const changeType = (e: string, options: any) => {
  //获取上级菜单id
  console.log(11111111)
  formState.menuType.value = e;
  menuType.value = options.type;
  formState.menuLogo.value = undefined;
  if (options.type == 2) {
    isMenu.value = false;
  } else {
    isMenu.value = true;
  }
};

const getDetail = async () => {
  if (route.query.type === "add") {
    (formState.menuName.value = ""),
      (formState.menuSuperior.value = null),
      (menuType.value = 1),
      (formState.menuType.value = "菜单"),
      (formState.menuLogo.value = ""),
      (formState.menuAddress.value = ""),
      (formState.routePath = ""),
      (formState.menuSort.value = ""),
      (formState.isShow.value = true),
      // formState.isAuth.value = false,
      (formState.menuIcon.value = ""),
      (formState.component.value = ""),
      (formState.redirect.value = ""),
      (formState.meta.value = ""),
      (formState.id = "");
    formState.parentId = "";
  } else {
    const data = await request.fetchMenuDetail({ id: route.query.id });
    selectApiList.value = data.apis || [];
    menuType.value = data.menuType;
    (formState.menuName.value = data.menuName);
    (menuType.value = data.menuType);
    (formState.menuType.value = data.menuType === 2 ? "按钮" : (data.menuType == 1 ? "菜单" : "按钮菜单"));
    (formState.menuLogo.value = data.permIdentity);
    (formState.menuAddress.value = data.routePath);
    (formState.routePath = data.routePath);
    (formState.menuSort.value = data.sortNum);
    (formState.isShow.value = data.isShow);
    // formState.isAuth.value = data.isAuth,
    (formState.component.value = data.component);
    (formState.redirect.value = data.redirect);
    (formState.meta.value = data.meta);
    (formState.menuIcon.value = data.iconClass);
    (formState.menuSuperior.value = data.parentMenuName);
    (formState.id = data.id);
    (formState.parentId = data.parentId);
    formState.entryPage.value = data.entryPage;
  }
};

// 上传图片返回值
const uploadFinished = (data: any) => {
  fileList.value = data;
};

//打开api选择弹窗
const selectApi = () => {
  buttons.value = [
    {
      text: "确定",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  isVisible.value = true;
  nextTick(() => {
    selectApiTables.value.selectedRowKeys =
      selectApiList.value.length &&
      selectApiList.value.map((item: any) => {
        return item.id;
      });
  });
};

//搜索api名称
const onSearch = async (e: any) => {
  //搜索获取数据参数配置
  getRecord();
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  pageNumber.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRecord();
};

//关闭单个
const closeItem = (i: any) => {
  selectApiList.value = selectApiList.value.filter((item: any) => item != i);
  selectApiTables.value.selectedRowKeys = selectApiTables.value.selectedRowKeys.filter(
    (item: any) => item != i.id
  );
  apiIds.value = selectApiTables.value.selectedRowKeys;
};

const closeAll = () => {
  selectApiList.value = [];
  selectApiTables.value.selectedRowKeys = [];
};

const saveSetting = async (msg: dataSourceType) => {
  // 新添或编辑菜单调取接口
  //保存
  menuAddFrom.value
    .validate()
    .then(() => {
      const params = {
        menuName: formState.menuName.value,
        menuType: menuType.value,
        pagePath: formState.menuAddress.value,
        parentId: formState.parentId,
        permIdentity: formState.menuLogo.value,
        routePath: formState.menuAddress.value,
        sortNum: formState.menuSort.value,
        component: formState.component.value,
        redirect: formState.redirect.value,
        meta: formState.meta.value,
        isShow: formState.isShow.value,
        isAuth: true,
        id: formState.id,
        iconClass: formState.menuIcon.value,
        // apiIds: apiIds.value,
        entryPage: formState.entryPage.value,
      };

      request[route.query.type === "edit" ? "fetchMenuUpdate" : "fetchMenuAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            router.push({
              path: "./menus",
            });
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    })
    .catch(() => { });
};

const buttonMessage = async (msg: dataSourceType) => {
  selectApiList.value =
    configData.records.length &&
    configData.records.filter((item: dataSourceType) => {
      if (rowSelection.value.findIndex((jitem) => jitem === item.id) != -1) {
        return true;
      }
    });

  isVisible.value = false;
  apiIds.value = rowSelection.value;
};

//取消返回
const cancle = () => {
  router.push({
    path: "./menus",
  });
};

const getMethod = (num: number) => {
  let text = "";
  switch (num) {
    case 1:
      text = "GET";
      break;
    case 2:
      text = "POST";
      break;
    case 3:
      text = "DELETE ";
      break;
    case 4:
      text = "UPDATE ";
      break;
    case 5:
      text = "PUT ";
      break;
    default:
      text = "";
  }
  return text;
};

const getRecord = async () => {
  // 获取表格数据
  const data: {} = {
    pageNumber: pageNumber.value || 0,
    pageSize: pageSize.value || 10,
    apiName: apiName.value || "",
  };
  const telData = (await request.fetchApiList(data)) || {};
  let reqData = telData;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item.middleDto,
      address: item.apiUrl,
      methods: getMethod(item.requestMethod),
      name: item.apiName,
      remark: item.useScene,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;

  configData.records = records;
  //selectApiTables.value.selectedRowKeys = [];
};

//computed
rowSelection = computed(() => {
  return selectApiTables.value.selectedRowKeys;
});

onMounted(() => {
  routerPerm().includes("saveAble") ? (saveAble.value = false) : (saveAble.value = true);
  init();
  getMenuAllTree();
  getDetail();
  getRecord();
  useFixeWidth();
});
</script>

<style lang="less" scoped>
.menu-add-edit {
  display: flex;
  flex-direction: row;
  padding: 48px 24px;
  background: #ffffff;
  height: calc(100% - 138px);
  display: flex;
  justify-content: center;
  overflow-y: auto;
}

.saveBtn {
  position: fixed;
  bottom: 0;
  height: 48px;
  background-color: #fff;
  box-shadow: 0px -12px 48px 16px rgba(0, 0, 0, 0.03),
    0px -9px 28px 0px rgba(0, 0, 0, 0.05), 0px -6px 16px -8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.closeAll {
  margin-top: 16px;
  width: 120px;
}

.header-content {
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  margin-bottom: 16px;
  padding: 16px;

  .searchContent {
    margin-top: 16px;
  }
}

.selctapi-list {
  margin-top: 8px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.baseTable {
  position: relative;
}

.baseTable .aTable {
  max-height: 450px;
  height: fit-content;
  overflow: auto;
}

::v-deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 60%;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 96px;
    text-align: right;
  }
}

::v-deep(.ant-form-item:last-child) {
  padding-bottom: 24px;
}
</style>
